<template>
    <div class="user_info_form_container">
        <el-form :model="userForm" status-icon :rules="rules" ref="userForm" label-width="70px"
                 class="demo-ruleForm" style="padding-top: 18px;">
            <el-form-item label="账号" prop="loginId">
                <el-input v-model="userForm.login_id" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="头像" prop="head_pic" style="margin-bottom: 5px;">
                <upload-cropper ref="uploadCropper" width="100px" height="100px"
                                :options="uploadCropperOptions" :data="uploadCropperData"
                                @success="uploadSuccess" />
            </el-form-item>
            <el-form-item label="性别">
                <el-select v-model="userForm.sex" placeholder="请选择性别" style="width: 100%;">
                    <el-option v-for="(item, index) in sexOptions" :key="index"
                               :label="item.label" :value="item.value"/>
                </el-select>
            </el-form-item>
            <el-form-item label="生日" prop="birth_day">
                <el-date-picker v-model="userForm.birth_day" type="date" placeholder="请选择生日"
                                value-format="yyyy-MM-dd" style="width: 100%"/>
            </el-form-item>
            <el-form-item label="电话" prop="phone">
                <el-input v-model="userForm.phone" autocomplete="off" clearable placeholder="请输入电话"/>
            </el-form-item>
            <el-form-item label="绑定微信" prop="wx_nickname" v-if="has_wxqr">
                <div style="display: flex;align-items: center;gap: 10px;">
                    <el-input v-model="userForm.wx_nickname" autocomplete="off" readonly placeholder="未绑定"
                              style="width: 100%;"/>
                    <el-button type="primary" v-show="userForm.wx_nickname ==='' || !userForm.wx_nickname "
                               @click="showWxQrCode" style="width: 80px;">{{ wx_bind_button_text }}
                    </el-button>
                </div>
                <div id="wxQrCode" v-show="is_showWxQrCode" style="width: 300px;height: 400px;margin-left: 25px;"></div>
            </el-form-item>
            <el-form-item v-if="showSubmit">
                <el-button type="primary" @click="confirm()">确认修改</el-button>
            </el-form-item>
        </el-form>

        <el-image-viewer v-if="imageViewerOption.visible" :z-index="imageViewerOption.zIndex"
                         :on-close="imageViewerOption.onClose" :url-list="imageViewerOption.urlList"/>
    </div>
</template>

<script>
import {mapState} from "vuex";
import fileApi from "@common/api/fileApi";
import wxLogin from "@common/components/wx/wxLogin";

export default {
    name: "UserInfoForm",
    props: {
        showSubmit: {
            type: Boolean,
            default: false,
        },
    },
    components: {
        CustomUpload: () => import("@common/components/upload/index.vue"),
        UploadCropper: () => import('@common/components/upload/UploadCropper'),
        ElImageViewer: () => import('element-ui/packages/image/src/image-viewer'),
    },
    data() {
        const _this = this;
        return {
            has_wxqr: false,
            wxLogin_setting: undefined,
            is_showWxQrCode: false,
            OP_WX_BIND: 'wx_bind',
            wx_bind_button_text: '现在绑定',
            userForm: {},
            rules: {
                password: [{required: true, message: '请输入当前密码', trigger: 'blur'}],
            },
            account_set_sid: _this.$utils.getAccountSetSid(),
            sexOptions: [
                {
                    value: 0,
                    label: "未知性别",
                },
                {
                    value: 1,
                    label: "男",
                },
                {
                    value: 2,
                    label: "女",
                },
            ],
            imageViewerOption: {
                visible: false,
                urlList: [],
                zIndex: 9999,
                onClose() {
                    _this.imageViewerOption = $.extend({}, _this.imageViewerOption, {
                        visible: false,
                        urlList: [],
                    });
                },
            },
            mainPicUploadOption: {
                ref: 'mainPicUpload',
                key: 'mainPic',
                action: fileApi.url.uploadFile + "?associate_biz_table=sys_user",
                headers: {
                    token: _this.$store.state.accessToken.token,
                    account_set_sid: _this.$utils.getAccountSetSid(),
                },
                listType: 'picture-card',
                tip: 'jpg或png格式图片',
                accept: 'image/png, image/jpeg',
                onSuccess(res, file) {
                    _this.userForm = $.extend({}, _this.userForm, {
                        head_pic: res.data.sid,
                    });
                    if (_this.$refs['columnMainPicUpload']) {
                        _this.$refs['columnMainPicUpload'].setFileList([{
                            url: file.url,
                        }]);
                    }
                },
                onRemove() {
                    delete _this.userForm.head_pic;
                    if (_this.$refs['columnMainPicUpload']) {
                        _this.$refs['columnMainPicUpload'].setFileList([]);
                    }
                },
                onPreview(file) {
                    if (file) {
                        _this.imageViewerOption = $.extend({}, _this.imageViewerOption, {
                            visible: true,
                            urlList: [file.url],
                        });
                    }
                },
            },
            uploadCropperOptions: {
                dialogOptions: {
                    title: "图标裁剪",
                    visible: false,
                },
                uploadOptions: {
                    accept: 'image/*',
                    limit: 1,
                    tip: '1:1正方形，jpg或png格式图片',
                },
                cropperOptions: {
                    outputType: 'png',
                    autoCropWidth: 100, // 默认生成截图框宽度
                    autoCropHeight: 100, // 默认生成截图框高度
                },
            },
            uploadCropperData: [],
        };
    },
    computed: {
        ...mapState(["userInfo"]),
    },
    mounted() {
        const _this = this;
        _this.account_set_sid = _this.$utils.getAccountSetSid();
        this.userForm = {
            login_id: _this.userInfo.login_id,
            sid: _this.userInfo.sid
        };
        let op = this.$route.query.op;
        if (this.OP_WX_BIND === op) {
            let user_sid = this.$route.query.user_sid;
            let code = this.$route.query.code;
            let state = this.$route.query.state;
            let subData = {code, state, user_sid};
            _this.fetchDataNoCatch(_this.$api.API_WxBind, subData).then(() => {
                _this.getMyInfo();
            });
        } else {
            // this.initWeixinQrCode();
            _this.getMyInfo();
        }
    },
    methods: {
        initWeixinQrCode() {
            const _this = this;
            _this.fetchDataNoCatch(_this.$api.Anon_GetWeixinOpenSetting).then(res => {
                let data = res.data || {};
                _this.has_wxqr = data.login_wx === 1;
                _this.wxLogin_setting = data;
            });
        },
        showWxQrCode() {
            const _this = this;
            _this.is_showWxQrCode = true;
            if (_this.has_wxqr) {
                wxLogin(document, {
                    self_redirect: false,//true：手机点击确认登录后可以在 iframe 内跳转到 redirect_uri，false：手机点击确认登录后可以在 top window 跳转到 redirect_uri。默认为 false。
                    id: "wxQrCode",//第三方页面显示二维码的容器id
                    appid: _this.wxLogin_setting.wx_open_appid,//应用唯一标识，在微信开放平台提交应用审核通过后获得
                    scope: 'snsapi_login',//应用授权作用域，拥有多个作用域用逗号（,）分隔，网页应用目前仅填写snsapi_login即可
                    redirect_uri: encodeURIComponent("http://www.guwen.biz/cr/autoLogin.html/#/myinfo?op=wx_bind&user_sid=" + this.userForm.sid),//重定向地址，需要进行UrlEncode
                    state: new Date().getTime(),//用于保持请求和回调的状态，授权请求后原样带回给第三方。该参数可用于防止csrf攻击（跨站请求伪造攻击），建议第三方带上该参数，可设置为简单的随机数加session进行校验
                    style: 'black',//提供"black"、"white"可选，默认为黑色文字描述。
                    href: '' //自定义样式链接，第三方可根据实际需求覆盖默认样式。
                });
            }
        },
        getMyInfo() {
            const _this = this;
            _this.fetchDataNoCatch(_this.$api.API_GetMyUserInfo).then(res => {
                _this.userForm = $.extend({}, res.data)
                _this.initUploadOption();
                let binds = res.data.bindList;
                if (binds && binds.length > 0) {
                    for (let i = 0; i < binds.length; i++) {
                        let b = binds[i];
                        if (b.ext_sys_name === 'weixin_open') {
                            _this.userForm.wx_nickname = b.nickname;
                            _this.wx_bind_button_text = "更换绑定";
                        }
                    }
                }
            });
        },
        initUploadOption() {
            const _this = this;
            let iconFileIds = [], data = [];
            if (_this.$utils.isNotEmpty(_this.userForm.head_pic)) {
                iconFileIds.push(_this.userForm.head_pic);
                data.push({
                    file_sid: _this.userForm.head_pic,
                })
            }
            _this.mainPicUploadOption = $.extend({}, _this.mainPicUploadOption, {
                fileIds: iconFileIds,
                index: `${new Date().getTime()}_min_pic`,
                key: `${new Date().getTime()}`,
            });
            _this.uploadCropperData = data;
        },
        uploadSuccess (data) {
            const _this = this;
            let head_pic = '';
            if (_this.$utils.isNotEmptyList(data)) {
                head_pic = data[0].sid;
            }
            _this.userForm = $.extend({}, _this.userForm, {
                head_pic,
            });
        },
        async confirm() {
            const _this = this;
            let valid = await _this.validateForm('userForm');
            if (valid) {
                let subData = $.extend({}, _this.userForm);
                return _this.fetchData(_this.$api.API_SaveMyUserInfo, subData).then(() => {
                    let uerInfo = $.extend({}, _this.userInfo, {
                        head_pic: subData.head_pic,
                    });
                    _this.$store.commit('setUserInfo', uerInfo);
                    _this.$bus.$emit("updateUserHeadPic")
                    _this.$message.success('修改成功！');
                    return true;
                }).catch(() => {
                    return false;
                });
            }
            return valid;
        },
    },
}
</script>

<style lang="less" rel="stylesheet/less">
.user_info_form_container {
    width: 100%;
    height: 100%;
    overflow: hidden;
}
</style>
